package org.kl.bf.service.basic;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.kl.bf.entity.basic.NotifyGroup;
import org.kl.bf.entity.basic.NotifyGroupUser;
import org.kl.bf.repository.basic.NotifyGroupDao;
import org.kl.bf.repository.basic.NotifyGroupUserDao;
import org.kl.bf.utils.CRUDUtils;
import org.kl.bf.utils.KLDynamicSpecifications;
import org.kl.bf.utils.KLSearchFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Component
@Transactional
public class NotifyGroupService {

	private NotifyGroupDao notifyGroupDao;
	
	@Autowired
	private NotifyGroupUserDao notifyGroupUserDao;
	
	public NotifyGroup getNotifyGroup(String guid) {
		return notifyGroupDao.findOne(guid);
	}

	public void saveNotifyGroup(NotifyGroup entity) {
		notifyGroupDao.save(entity);
	}

	public void deleteNotifyGroup(String guid) {
		notifyGroupDao.delete(guid);
	}
	
	public String multiDelete(String ids) {
		String[] idArray = StringUtils.split(ids, ",");
		int i = 0, j = 0;
		for (String id : idArray) {
			if (StringUtils.isNotBlank(id)) {
					List<NotifyGroupUser> UserList = notifyGroupUserDao.findByNotifyGroupId(id);
					j += UserList.size();
					notifyGroupUserDao.delete(UserList);
					notifyGroupDao.delete(id);
					i++; 
			}
		}
		return "删除" + i + "条记录,并且删除" + j + "条成员信息";
	}

	public List<NotifyGroup> getAllNotifyGroups() {
		return notifyGroupDao.findAll();
	}

	public Page<NotifyGroup> getNotifyGroup(Map<String, Object> searchParams, int pageNumber, int pageSize, String sortType,
			String orderType) {
		PageRequest pageRequest = CRUDUtils.buildPageRequest(pageNumber, pageSize, sortType, orderType);
		Specification<NotifyGroup> spec = buildSpecification(searchParams);

		return notifyGroupDao.findAll(spec, pageRequest);
	}

	/**
	 * 创建动态查询条件组合.
	 */
	private Specification<NotifyGroup> buildSpecification(Map<String, Object> searchParams) {
		Map<String, KLSearchFilter> filters = KLSearchFilter.parse(searchParams);
		Specification<NotifyGroup> spec = KLDynamicSpecifications.byKLSearchFilter(filters.values(), NotifyGroup.class);
		return spec;
	}

	@Autowired
	public void setNotifyGroupDao(NotifyGroupDao notifyGroupDao) {
		this.notifyGroupDao = notifyGroupDao;
	}

}
